package com.xiaolei.fastnio.library.Client

import java.nio.ByteBuffer
import java.nio.channels.SocketChannel
import java.util.*

/**
 * 连接进来的会话
 */
class Session(private val clientChannel: SocketChannel,
              val sessionId: String = UUID.randomUUID().toString())
{
    var isAlive: Boolean = false
    fun write(data: ByteArray)
    {
        write(ByteBuffer.wrap(data))
    }

    fun write(data: ByteArray, offset: Int, len: Int)
    {
        write(data.copyOfRange(offset, offset + len))
    }

    fun write(buffer: ByteBuffer)
    {
        if (isAlive)
        {
            clientChannel.write(buffer)
            // 如果还有数据，就一直死循环，一定要全部发出去
            while (buffer.remaining() > 0)
            {
                Thread.sleep(10)
                clientChannel.write(buffer)
            }
        } else
            throw IllegalStateException("此会话已经关闭")
    }

    fun close()
    {
        isAlive = false
        clientChannel.close()
    }
}